package cn.alise.qdp.service.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.xml.security.utils.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import cn.alise.consts.ConfigConsts;
import cn.alise.enums.EnumClass;
import cn.alise.exception.ServiceException;
import cn.alise.util.DateUtil;
import cn.alise.util.FileType;
import cn.alise.util.FileTypeJudge;

/**
 * 文件上传服务类
 */
@SuppressWarnings("restriction")
@Service
@Transactional(rollbackFor = Exception.class)
public class UploadService {

	protected final Logger logger = Logger.getLogger(this.getClass());

	// 图片前缀
	private static final String PRE_IMG = "img";
	
	@Value("${lacp.saveimg.path:0}")
	private String lacp_SAVEIMG_PATH;
	
	// 文件前缀
	private static final String PRE_FILE = "file";

	// 图片路劲层级分隔符
//	private static String separator = "/";
	
	/**
	 * 将二进制的图片字符串保存为图片
	 * 
	 * @param b
	 * @param memberId
	 * @return
	 * @throws Exception
	 */
	public String save(byte[] b, Long organId) throws Exception {
		FileType fileType = FileTypeJudge.getType(b);
		if (fileType == null) {
			throw new RuntimeException("图片文件格式非法");
		}
		
		String path = ConfigConsts.lacp_SAVEIMG_PATH+ "/" + PRE_IMG + "/" + organId;
		String fileName = UUID.randomUUID().toString() + "." + fileType.name().toLowerCase();

		// 将图片保存至本地硬盘(不使用FTP)
		// InputStream inputStream = new ByteArrayInputStream(b);
		// FTPClient ftp = this.getFTPconnect(path);
		// this.upload(ftp, fileName, inputStream);

		File file = new File(path);
		if (!file.exists() && !file.isDirectory()) {
			file.mkdirs();
		}
		File imageFile = new File(path + "/" + fileName);
		BASE64Decoder d = new BASE64Decoder();
		byte[] bs;
		OutputStream os = null;
		try {
			// 保存
			bs = d.decodeBuffer(Base64.encode(b));
			os = new FileOutputStream(imageFile);
			os.write(bs);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return PRE_IMG + "/" + organId + "/" + fileName;
	}
	
	/**
	 * 将二进制的图片字符串保存为图片
	 * 
	 * @param b
	 * @param memberId
	 * @return
	 * @throws Exception
	 */
	public String saveImg(String imgUrl, String preImg) throws Exception {
		
		if (!StringUtils.isEmpty(imgUrl)) {
			
			byte[] bs;
			OutputStream os = null;
			
			Date nowDate = new Date();
			String yyyy = DateUtil.formatDate(nowDate, "yyyy");
			String mm = DateUtil.formatDate(nowDate, "MM");
			String dd = DateUtil.formatDate(nowDate, "dd");
			
			String fileName = "";
			
			try {
				String imgName = UUID.randomUUID().toString().replaceAll("-", "");
		 	    String base64ImageStr = imgUrl;
		 		base64ImageStr = base64ImageStr.replaceFirst("data:(.+?);base64,", "");
		 		
		 		byte [] decodeBase64ImageStr = Base64.decode(base64ImageStr);
		 				
				FileType fileType = FileTypeJudge.getType(decodeBase64ImageStr);
				if (fileType == null) {
					throw new RuntimeException("图片文件格式非法");
				}
				
				String path = ConfigConsts.lacp_SAVEIMG_PATH + "/" + PRE_IMG + "/" + preImg + "/" + yyyy + "/" + mm + "/" + dd;
				fileName = imgName + "." + fileType.name().toLowerCase();
	
				File file = new File(path);
				if (!file.exists() && !file.isDirectory()) {
					file.mkdirs();
				}
				File imageFile = new File(path + "/" + fileName);
				BASE64Decoder d = new BASE64Decoder();
			
				// 保存
				bs = d.decodeBuffer(Base64.encode(decodeBase64ImageStr));
				os = new FileOutputStream(imageFile);
				os.write(bs);
				
			} catch (Exception e) {
				logger.error(e);
				throw e;
			} finally {
				if (os != null) {
					try {
						os.close();
					} catch (IOException e) {
						logger.error("关闭图片流异常！" + e);
					}
				}
			}

			return PRE_IMG + "/" + preImg + "/" + yyyy + "/" + mm + "/" + dd + "/" + fileName;
		} else {
			return "";
		}
		
	}
	
	/**
	 * 保存视频
	 * @return
	 * @throws Exception 
	 */
	public String saveVideo(HttpServletRequest request) throws Exception {
		
		String path = lacp_SAVEIMG_PATH + "/";
		String fileName = "";
		
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		Iterator<String> iter = multiRequest.getFileNames();
		while (iter.hasNext()) {
			MultipartFile file = multiRequest.getFile(iter.next());
			int size=(int) file.getSize()/1024;
			if(size==0) {
				size = 1;
			}
			if (file != null) {
				String myFileName = file.getOriginalFilename();
				if (myFileName.trim() != "") {
					fileName = PRE_FILE + "/" + System.currentTimeMillis() + "_"
							+ file.getOriginalFilename();
					File localFile = new File(path + "/" + fileName);
					if (!localFile.getParentFile().exists()) {
						localFile.getParentFile().mkdirs();
					}
					localFile.createNewFile();
					file.transferTo(localFile);
				}
			}
		}
		
		return fileName;
	}
	
	/** 
     * 将文件转成base64 字符串 
     * @param path文件路径 
     * @return  *  
     * @throws Exception 
     */  
     
    public static String encodeBase64File(String path) throws Exception {  
    	File file = new File(path);;  
    	FileInputStream inputFile = new FileInputStream(file);  
    	byte[] buffer = new byte[(int) file.length()];  
    	inputFile.read(buffer);  
    	inputFile.close();  
    	return new BASE64Encoder().encode(buffer);  
    }

	//图片转化成base64字符串  
    public  String GetImageStr(String imgFile) throws ServiceException  
    {//将图片文件转化为字节数组字符串，并对其进行Base64编码处理  
        //String imgFile = "d://test.jpg";//待处理的图片  
        InputStream in = null;  
        byte[] data = null; 
        File file = new File(ConfigConsts.lacp_SAVEIMG_PATH+ "/" +imgFile);
        if (!file.exists()) {
        	logger.error("异常,"+ file +"文件未找到！");
        	throw new ServiceException(EnumClass.ResultCodeType.SYSERROR.getKey(), EnumClass.ResultCodeType.SYSERROR.getValue());
        } 
        //读取图片字节数组  
        try   
        {  
            in = new FileInputStream(file);          
            data = new byte[in.available()];  
            in.read(data);  
            in.close();  
        }   
        catch (IOException e)   
        {  
            e.printStackTrace();  
        }  
        //对字节数组Base64编码  
        BASE64Encoder encoder = new BASE64Encoder();  
        return encoder.encode(data);//返回Base64编码过的字节数组字符串  
    }  
}
